package com.leetcode.math;

public class MaximumSwap {
    public int maximumSwap(int num){
        char[] chars = String.valueOf(num).toCharArray();
        int len = chars.length;
        int[] maxArr = new int[len];
        int maxInd = len - 1;
        for(int i = len - 1; i >= 0; i--){
            if(chars[i] > chars[maxInd]){
                maxInd = i;
            }
            maxArr[i] = maxInd;
        }
        for(int i = 0; i < len; i++){
            if(chars[i] < chars[maxArr[i]]){
                swap(chars, i, maxArr[i]);
                break;
            }
        }
        return Integer.parseInt(new String(chars));
    }

    private void swap(char[] chars, int i, int j) {
        char tmp = chars[i];
        chars[i] = chars[j];
        chars[j] = tmp;
    }
}
